package com.pan.crawler.impl8;

import com.pan.crawler.Directory;
import com.pan.entity.BookDirectory;
import com.pan.entity.Chapter;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.edge.EdgeDriver;

import java.time.Duration;
import java.util.ArrayList;
import java.util.List;

public class DirectoryImpl8 implements Directory {

    private String webUrl = "m.wu62.org";
    @Override
    public BookDirectory get(String url) {
        if (url.indexOf(webUrl) == -1){
            throw new RuntimeException("网址错误："+url+"该网址不是"+webUrl+"网址");
        }
        BookDirectory resultDirectory = new BookDirectory();

        List<Chapter> bookChapterList = new ArrayList<>();
        EdgeDriver edgeDriver = new EdgeDriver();
        edgeDriver.manage().timeouts().implicitlyWait(Duration.ofSeconds(10));
        edgeDriver.navigate().to(url);
        WebElement blockTxt2 = edgeDriver.findElement(By.className("block_txt2"));
        WebElement h2 = blockTxt2.findElement(By.tagName("h2"));
        resultDirectory.setBookName(h2.getText());

//        从目录页里获取完整的目录信息
        WebElement selectElement = edgeDriver.findElement(By.tagName("select"));
        List<WebElement> optionElements = selectElement.findElements(By.tagName("option"));
        String[] pageItemUrl = optionElements.stream().map(element-> element.getAttribute("value")).toArray(String[]::new);
        int i = 0;
        for (String directoryPageUrl : pageItemUrl) {
            edgeDriver.navigate().to(directoryPageUrl);
            //有两个class属性为chapter的目录，这里要取第二个
            List<WebElement> chapters = edgeDriver.findElements(By.className("chapter"));
            WebElement chapterList = chapters.get(1);
            List<WebElement> aList = chapterList.findElements(By.tagName("a"));
            for (WebElement a : aList) {
                String title = a.getText();
                String href = a.getAttribute("href");
                bookChapterList.add(new Chapter(i++, title, href));
            }
        }

        resultDirectory.setChapterList(bookChapterList);
        edgeDriver.quit();
        return resultDirectory;
    }
}
